; BMP A app to display BMP Files.
; Thanks to me239
org 0x8000
bits 16
%include "system.inc"
db 'NT'
ENTRY_MAIN:
	; Switch Video Modes
	mov word [LoadAddress],0
	mov ax,si
	mov bx,0
	mov cx,33690
	call os_load_file
	jc no_file
	mov	ax, 0013h
	int	10h
pusha				   ; save the regs
	push	ds
	push	es
	mov	si,33690		   ; make sure si as the image address
	cmp	word [si+00h],4D42h	   ; test for 'BM' to make sure its a BMP file.
	jnz	BmpError		   ; if jump to exit with error
	mov	bx,[si+12h]		   ; start of header + 18 = width
	mov	bp,[si+16h]		   ; start of header + 22 = depth
	cmp	bx,320
	ja	BmpError
	cmp	bp,200
	ja	BmpError
	cmp	word [si+1Ch],8 	   ; start of header + 28 = bpp
	jnz	BmpError
	mov	si,0036h		   ;start of header + 54 = start of palette
	add	si,33690
	mov	cx,256			   ;number of colors for patette
	mov	dx,03C8h
	mov	al,0
	out	dx,al
	inc	dx
SetPalete:
	mov	al,[si+2]		   ; red
	shr	al,2
	out	dx,al
	mov	al,[si+1]		   ; green
	shr	al,2
	out	dx,al
	mov	al,[si] 		   ; blue
	shr	al,2
	out	dx,al
	add	si,4
	loop	SetPalete

	push	0A000h
	pop	es
	lea	dx,[bx+3]		   ; round bmp width ;)
	and	dx,-4
	imul	di,bp,320
	add	di,[LoadAddress]	   ; this is the X Y offset of the screen
new_line:
	sub	di,320
	pusha
	mov	cx,bx
	rep	movsb
	popa
	add	si,dx
	dec	bp
	jnz	new_line
ExitOK:
	clc
	pop	es
	pop	ds
	popa
	xor ax,ax
	int 0x16
	mov ah,0x00
	mov al,0x03
	int 0x10
	xor bl,bl
	mov ax,0x1112
	int 0x10
	mov ax,1003h
	mov bx,0
	int 0x10
	call os_show_cursor
	int 0x20

BmpError:
	stc
	pop	es
	pop	ds
	popa
	mov ah,0x00
	mov al,0x03
	int 0x10
	xor bl,bl
	mov ax,0x1112
	int 0x10
	mov ax,1003h
	mov bx,0
	int 0x10
	int 0x20
	LoadAddress dw 0
no_file:
	mov si,nofile
	call os_print_string
	int 0x20
	nofile db 'BMP <FILENAME> : Display a Bitmap Image',13,10,'xOS BMP Viewer (C) me239 under GPLv3',0